namespace NFTRedit
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;

    public class MainForm : Form
    {
        string file = "";
        //private AboutForm aboutForm;
        private ToolStripMenuItem aboutToolStripMenuItem;
        private ToolStripMenuItem autoApplyToolStripMenuItem;
        private Bitmap backBuffer;
        private static Bitmap backDot;
        private static Color backgroundColor = Color.FromArgb(0xef, 0xde, 0xc6);
        private ToolStripMenuItem characterMapToolStripMenuItem;
        private IContainer components;
        private ToolStripMenuItem customToolStripMenuItem;
        private Bitmap dialogBuffer;
        private string dumpFileName = "dump.bmp";
        private ToolStripMenuItem dumpTilesToolStripMenuItem;
        private ToolStripMenuItem dumpToBitmapToolStripMenuItem;
        private ToolStripMenuItem dumpToClipboardToolStripMenuItem;
        private ToolStripMenuItem exitToolStripMenuItem;
        private string fileName = "";
        private ToolStripMenuItem fileToolStripMenuItem;
        private NFTRedit.Font font;
        private static Bitmap foreDot = new Bitmap(1, 1);
        private static Color foregroundColor = Color.FromArgb(0, 0, 0);
        private ToolStripMenuItem helpToolStripMenuItem;
        private ToolStripMenuItem importFromBitmapToolStripMenuItem;
        private ToolStripMenuItem importFromClipboardToolStripMenuItem;
        private ToolStripMenuItem importTilesToolStripMenuItem;
        private Label label1;
        private Label label2;
        private ToolStripMenuItem loadTableToolStripMenuItem;
        private MapForm mapForm;
        private MenuStrip menuStrip1;
        private int mode = 1;
        private OpenFileDialog openDumpDialog;
        private OpenFileDialog openFileDialog;
        private OpenFileDialog openTableDialog;
        private ToolStripMenuItem openToolStripMenuItem;
        private ToolStripMenuItem optionsToolStripMenuItem;
        private Panel panelDialogBox;
        private PropertiesForm propertiesForm;
        private ToolStripMenuItem propertiesToolStripMenuItem;
        private ToolStripMenuItem rawBytesToolStripMenuItem;
        private ToolStripMenuItem saveAsToolStripMenuItem;
        private SaveFileDialog saveDumpDialog;
        private SaveFileDialog saveFileDialog;
        private ToolStripMenuItem saveTableAsToolStripMenuItem;
        private SaveFileDialog saveTableDialog;
        private ToolStripMenuItem saveTableToolStripMenuItem;
        private ToolStripMenuItem saveToolStripMenuItem;
        private ToolStripMenuItem shiftJISToolStripMenuItem;
        private CharacterTable table;
        private string tableFileName = "custom.tbl";
        private ToolStripMenuItem tableToolStripMenuItem;
        private TextBox textBoxLine;
        private TextBox textBoxLineLength;
        private TextBox textBoxPadding;
        private ToolStripMenuItem toolsToolStripMenuItem;
        private ToolStripSeparator toolStripMenuItem1;
        private ToolStripMenuItem unicodeBEToolStripMenuItem;
        private ToolStripMenuItem unicodeLEToolStripMenuItem;
        private List<char> validDec = new List<char>(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });

        static MainForm()
        {
            foreDot.SetPixel(0, 0, foregroundColor);
            backDot = new Bitmap(1, 1);
            backDot.SetPixel(0, 0, backgroundColor);
        }

        public MainForm()
        {
            this.InitializeComponent();
            this.table = new CharacterTable();
            //this.aboutForm = new AboutForm();
            this.ResizeDialogBox();
        }
        public MainForm(string f)
        {
            this.InitializeComponent();
            this.table = new CharacterTable();
            //this.aboutForm = new AboutForm();
            this.ResizeDialogBox();
            this.file = f;
            fileName = f;
        }

        private void AboutToolStripMenuItemClick(object sender, EventArgs e)
        {
            //this.aboutForm.ShowDialog();
        }

        private void AutoApplyToolStripMenuItemClick(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            item.Checked = !item.Checked;
            Utility.AutoApply = item.Checked;
        }

        private void CharacterMapToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (this.font == null)
            {
                MessageBox.Show("Open a font file first.");
            }
            else
            {
                try
                {
                    if ((this.mapForm == null) || this.mapForm.IsDisposed)
                    {
                        this.mapForm = new MapForm();
                        this.mapForm.Show(this, this.font, this.table);
                    }
                    else
                    {
                        this.mapForm.Focus();
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show("The character map could not be displayed.\r\nMake sure you have the latest .NET Framework installed.\nOtherwise, post the following message in the thread,\r\nalong with the NFTR file you are using.");
                    throw exception;
                }
            }
        }

        private void CustomToolStripMenuItemClick(object sender, EventArgs e)
        {
            this.mode = 4;
            this.rawBytesToolStripMenuItem.Checked = false;
            this.shiftJISToolStripMenuItem.Checked = false;
            this.unicodeLEToolStripMenuItem.Checked = false;
            this.unicodeBEToolStripMenuItem.Checked = false;
            this.customToolStripMenuItem.Checked = true;
            this.RedrawDialogBox();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        public Bitmap DumpTiles()
        {
            if (this.font == null)
            {
                return null;
            }
            int num = 20;
            int num2 = (int) Math.Ceiling((double) ((1.0 * this.font.Tiles.Length) / ((double) num)));
            Bitmap image = new Bitmap((num * (this.font.MaxWidth + 1)) + 1, (num2 * (this.font.MaxHeight + 1)) + 1);
            Graphics graphics = Graphics.FromImage(image);
            graphics.Clear(Color.White);
            Brush brush = new SolidBrush(this.BackColor);
            for (int i = 0; i < this.font.Tiles.Length; i++)
            {
                int x = ((i % num) * (this.font.MaxWidth + 1)) + 1;
                int y = ((i / num) * (this.font.MaxHeight + 1)) + 1;
                graphics.FillRectangle(brush, x, y, this.font.MaxWidth, this.font.MaxHeight);
                graphics.DrawImageUnscaled(this.font.Tiles[i], x, y);
            }
            graphics.Dispose();
            return image;
        }

        private void DumpToBitmapToolStripMenuItemClick(object sender, EventArgs e)
        {
            this.saveDumpDialog.FileName = this.dumpFileName;
            if (this.saveDumpDialog.ShowDialog() == DialogResult.OK)
            {
                Bitmap bitmap = new Bitmap(this.DumpTiles());
                bitmap.Save(this.saveDumpDialog.FileName);
                bitmap.Dispose();
                this.dumpFileName = this.saveDumpDialog.FileName;
            }
        }

        private void DumpToClipboardToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (this.font != null)
            {
                Clipboard.SetImage(this.DumpTiles());
            }
        }

        private void ExitToolStripMenuItemClick(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void ImportFromBitmapToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (this.openDumpDialog.ShowDialog() == DialogResult.OK)
            {
                Bitmap image = new Bitmap(this.openDumpDialog.FileName);
                this.ImportTiles(image);
                image.Dispose();
                this.dumpFileName = this.openDumpDialog.FileName;
            }
        }

        private void ImportFromClipboardToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (this.font != null)
            {
                try
                {
                    Image image = Clipboard.GetImage();
                    if (image == null)
                    {
                        MessageBox.Show("Unable to read data from clipboard.");
                    }
                    else
                    {
                        this.ImportTiles(image);
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show("Unable to read data from clipboard.\n" + exception.Message);
                }
            }
        }

        public void ImportTiles(Image image)
        {
            int num = 20;
            int num2 = (int) Math.Ceiling((double) ((1.0 * this.font.Tiles.Length) / ((double) num)));
            int num3 = (num * (this.font.MaxWidth + 1)) + 1;
            int num4 = (num2 * (this.font.MaxHeight + 1)) + 1;
            if (image.Width != num3)
            {
                MessageBox.Show(string.Concat(new object[] { "Image width of ", image.Width, " does not match expected width ", num3, "." }));
            }
            else if (image.Height != num4)
            {
                MessageBox.Show(string.Concat(new object[] { "Image height of ", image.Height, " does not match expected height ", num4, "." }));
            }
            else
            {
                Graphics graphics;
                ColorMap[] map = new ColorMap[this.font.Dots.Length];
                for (int i = 0; i < this.font.Dots.Length; i++)
                {
                    Bitmap bitmap = new Bitmap(1, 1);
                    graphics = Graphics.FromImage(bitmap);
                    graphics.Clear(this.BackColor);
                    graphics.DrawImageUnscaled(this.font.Dots[i], 0, 0);
                    graphics.Dispose();
                    map[i] = new ColorMap();
                    map[i].OldColor = bitmap.GetPixel(0, 0);
                    map[i].NewColor = this.font.Dots[i].GetPixel(0, 0);
                    bitmap.Dispose();
                }
                ImageAttributes imageAttr = new ImageAttributes();
                imageAttr.SetRemapTable(map);
                Bitmap bitmap2 = new Bitmap(image.Width, image.Height);
                Rectangle destRect = new Rectangle(0, 0, image.Width, image.Height);
                graphics = Graphics.FromImage(bitmap2);
                graphics.Clear(Color.Transparent);
                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttr);
                graphics.Dispose();
                for (int j = 0; j < this.font.Tiles.Length; j++)
                {
                    int srcX = ((j % num) * (this.font.MaxWidth + 1)) + 1;
                    int srcY = ((j / num) * (this.font.MaxHeight + 1)) + 1;
                    destRect = new Rectangle(0, 0, this.font.MaxWidth, this.font.MaxHeight);
                    graphics = Graphics.FromImage(this.font.Tiles[j]);
                    graphics.Clear(Color.Transparent);
                    graphics.DrawImage(bitmap2, destRect, srcX, srcY, this.font.MaxWidth, this.font.MaxHeight, GraphicsUnit.Pixel);
                    graphics.Dispose();
                }
                this.RedrawDialogBox();
                this.UpdateMapForm();
            }
        }

        private void InitializeComponent()
        {
            ComponentResourceManager manager = new ComponentResourceManager(typeof(MainForm));
            this.openFileDialog = new OpenFileDialog();
            this.menuStrip1 = new MenuStrip();
            this.fileToolStripMenuItem = new ToolStripMenuItem();
            this.openToolStripMenuItem = new ToolStripMenuItem();
            this.saveToolStripMenuItem = new ToolStripMenuItem();
            this.saveAsToolStripMenuItem = new ToolStripMenuItem();
            this.dumpTilesToolStripMenuItem = new ToolStripMenuItem();
            this.dumpToBitmapToolStripMenuItem = new ToolStripMenuItem();
            this.dumpToClipboardToolStripMenuItem = new ToolStripMenuItem();
            this.importTilesToolStripMenuItem = new ToolStripMenuItem();
            this.importFromBitmapToolStripMenuItem = new ToolStripMenuItem();
            this.importFromClipboardToolStripMenuItem = new ToolStripMenuItem();
            this.toolStripMenuItem1 = new ToolStripSeparator();
            this.exitToolStripMenuItem = new ToolStripMenuItem();
            this.tableToolStripMenuItem = new ToolStripMenuItem();
            this.rawBytesToolStripMenuItem = new ToolStripMenuItem();
            this.shiftJISToolStripMenuItem = new ToolStripMenuItem();
            this.unicodeLEToolStripMenuItem = new ToolStripMenuItem();
            this.unicodeBEToolStripMenuItem = new ToolStripMenuItem();
            this.customToolStripMenuItem = new ToolStripMenuItem();
            this.loadTableToolStripMenuItem = new ToolStripMenuItem();
            this.saveTableToolStripMenuItem = new ToolStripMenuItem();
            this.saveTableAsToolStripMenuItem = new ToolStripMenuItem();
            this.toolsToolStripMenuItem = new ToolStripMenuItem();
            this.characterMapToolStripMenuItem = new ToolStripMenuItem();
            this.propertiesToolStripMenuItem = new ToolStripMenuItem();
            this.helpToolStripMenuItem = new ToolStripMenuItem();
            this.aboutToolStripMenuItem = new ToolStripMenuItem();
            this.panelDialogBox = new Panel();
            this.textBoxLine = new TextBox();
            this.saveFileDialog = new SaveFileDialog();
            this.openTableDialog = new OpenFileDialog();
            this.saveTableDialog = new SaveFileDialog();
            this.openDumpDialog = new OpenFileDialog();
            this.saveDumpDialog = new SaveFileDialog();
            this.textBoxLineLength = new TextBox();
            this.label1 = new Label();
            this.label2 = new Label();
            this.textBoxPadding = new TextBox();
            this.optionsToolStripMenuItem = new ToolStripMenuItem();
            this.autoApplyToolStripMenuItem = new ToolStripMenuItem();
            this.menuStrip1.SuspendLayout();
            base.SuspendLayout();
            this.openFileDialog.DefaultExt = "nftr";
            this.openFileDialog.Filter = "NFTR files|*.nftr|All files|*.*";
            this.openFileDialog.Title = "Load Table";
            this.menuStrip1.Items.AddRange(new ToolStripItem[] { this.fileToolStripMenuItem, this.tableToolStripMenuItem, this.toolsToolStripMenuItem, this.optionsToolStripMenuItem, this.helpToolStripMenuItem });
            this.menuStrip1.Location = new Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new Size(0x144, 0x18);
            this.menuStrip1.TabIndex = 0;
            this.menuStrip1.Text = "menuStrip1";
            this.fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { this.openToolStripMenuItem, this.saveToolStripMenuItem, this.saveAsToolStripMenuItem, this.dumpTilesToolStripMenuItem, this.importTilesToolStripMenuItem, this.toolStripMenuItem1, this.exitToolStripMenuItem });
            this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
            this.fileToolStripMenuItem.Size = new Size(0x23, 20);
            this.fileToolStripMenuItem.Text = "&File";
            this.openToolStripMenuItem.Name = "openToolStripMenuItem";
            this.openToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.O;
            this.openToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.openToolStripMenuItem.Text = "&Open...";
            this.openToolStripMenuItem.Click += new EventHandler(this.OpenToolStripMenuItemClick);
            this.saveToolStripMenuItem.Enabled = false;
            this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
            this.saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
            this.saveToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.saveToolStripMenuItem.Text = "&Save";
            this.saveToolStripMenuItem.Click += new EventHandler(this.SaveToolStripMenuItemClick);
            this.saveAsToolStripMenuItem.Enabled = false;
            this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
            this.saveAsToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.saveAsToolStripMenuItem.Text = "Save &As...";
            this.saveAsToolStripMenuItem.Click += new EventHandler(this.SaveAsToolStripMenuItemClick);
            this.dumpTilesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { this.dumpToBitmapToolStripMenuItem, this.dumpToClipboardToolStripMenuItem });
            this.dumpTilesToolStripMenuItem.Enabled = false;
            this.dumpTilesToolStripMenuItem.Name = "dumpTilesToolStripMenuItem";
            this.dumpTilesToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.dumpTilesToolStripMenuItem.Text = "&Dump Tiles";
            this.dumpToBitmapToolStripMenuItem.Name = "dumpToBitmapToolStripMenuItem";
            this.dumpToBitmapToolStripMenuItem.Size = new Size(0x86, 0x16);
            this.dumpToBitmapToolStripMenuItem.Text = "To &Bitmap...";
            this.dumpToBitmapToolStripMenuItem.Click += new EventHandler(this.DumpToBitmapToolStripMenuItemClick);
            this.dumpToClipboardToolStripMenuItem.Name = "dumpToClipboardToolStripMenuItem";
            this.dumpToClipboardToolStripMenuItem.Size = new Size(0x86, 0x16);
            this.dumpToClipboardToolStripMenuItem.Text = "To &Clipboard";
            this.dumpToClipboardToolStripMenuItem.Click += new EventHandler(this.DumpToClipboardToolStripMenuItemClick);
            this.importTilesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { this.importFromBitmapToolStripMenuItem, this.importFromClipboardToolStripMenuItem });
            this.importTilesToolStripMenuItem.Enabled = false;
            this.importTilesToolStripMenuItem.Name = "importTilesToolStripMenuItem";
            this.importTilesToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.importTilesToolStripMenuItem.Text = "&Import Tiles";
            this.importFromBitmapToolStripMenuItem.Name = "importFromBitmapToolStripMenuItem";
            this.importFromBitmapToolStripMenuItem.Size = new Size(0x92, 0x16);
            this.importFromBitmapToolStripMenuItem.Text = "From &Bitmap...";
            this.importFromBitmapToolStripMenuItem.Click += new EventHandler(this.ImportFromBitmapToolStripMenuItemClick);
            this.importFromClipboardToolStripMenuItem.Name = "importFromClipboardToolStripMenuItem";
            this.importFromClipboardToolStripMenuItem.Size = new Size(0x92, 0x16);
            this.importFromClipboardToolStripMenuItem.Text = "From &Clipboard";
            this.importFromClipboardToolStripMenuItem.Click += new EventHandler(this.ImportFromClipboardToolStripMenuItemClick);
            this.toolStripMenuItem1.Name = "toolStripMenuItem1";
            this.toolStripMenuItem1.Size = new Size(0x95, 6);
            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
            this.exitToolStripMenuItem.ShortcutKeys = Keys.Alt | Keys.F4;
            this.exitToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.exitToolStripMenuItem.Text = "E&xit";
            this.exitToolStripMenuItem.Click += new EventHandler(this.ExitToolStripMenuItemClick);
            this.tableToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { this.rawBytesToolStripMenuItem, this.shiftJISToolStripMenuItem, this.unicodeLEToolStripMenuItem, this.unicodeBEToolStripMenuItem, this.customToolStripMenuItem });
            this.tableToolStripMenuItem.Name = "tableToolStripMenuItem";
            this.tableToolStripMenuItem.Size = new Size(0x2d, 20);
            this.tableToolStripMenuItem.Text = "Ta&ble";
            this.rawBytesToolStripMenuItem.Name = "rawBytesToolStripMenuItem";
            this.rawBytesToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.rawBytesToolStripMenuItem.Text = "&Raw Bytes";
            this.rawBytesToolStripMenuItem.Click += new EventHandler(this.RawBytesToolStripMenuItemClick);
            this.shiftJISToolStripMenuItem.Checked = true;
            this.shiftJISToolStripMenuItem.CheckState = CheckState.Checked;
            this.shiftJISToolStripMenuItem.Name = "shiftJISToolStripMenuItem";
            this.shiftJISToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.shiftJISToolStripMenuItem.Text = "&Shift-JIS";
            this.shiftJISToolStripMenuItem.Click += new EventHandler(this.ShiftJISToolStripMenuItemClick);
            this.unicodeLEToolStripMenuItem.Name = "unicodeLEToolStripMenuItem";
            this.unicodeLEToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.unicodeLEToolStripMenuItem.Text = "&Unicode (LE)";
            this.unicodeLEToolStripMenuItem.Click += new EventHandler(this.UnicodeLEToolStripMenuItemClick);
            this.unicodeBEToolStripMenuItem.Name = "unicodeBEToolStripMenuItem";
            this.unicodeBEToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.unicodeBEToolStripMenuItem.Text = "Unicode (&BE)";
            this.unicodeBEToolStripMenuItem.Click += new EventHandler(this.UnicodeBEToolStripMenuItemClick);
            this.customToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { this.loadTableToolStripMenuItem, this.saveTableToolStripMenuItem, this.saveTableAsToolStripMenuItem });
            this.customToolStripMenuItem.Name = "customToolStripMenuItem";
            this.customToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.customToolStripMenuItem.Text = "&Custom";
            this.customToolStripMenuItem.Click += new EventHandler(this.CustomToolStripMenuItemClick);
            this.loadTableToolStripMenuItem.Name = "loadTableToolStripMenuItem";
            this.loadTableToolStripMenuItem.Size = new Size(0x7d, 0x16);
            this.loadTableToolStripMenuItem.Text = "L&oad...";
            this.loadTableToolStripMenuItem.Click += new EventHandler(this.LoadTableToolStripMenuItemClick);
            this.saveTableToolStripMenuItem.Name = "saveTableToolStripMenuItem";
            this.saveTableToolStripMenuItem.Size = new Size(0x7d, 0x16);
            this.saveTableToolStripMenuItem.Text = "&Save";
            this.saveTableToolStripMenuItem.Click += new EventHandler(this.SaveTableToolStripMenuItemClick);
            this.saveTableAsToolStripMenuItem.Name = "saveTableAsToolStripMenuItem";
            this.saveTableAsToolStripMenuItem.Size = new Size(0x7d, 0x16);
            this.saveTableAsToolStripMenuItem.Text = "Save &As...";
            this.saveTableAsToolStripMenuItem.Click += new EventHandler(this.SaveTableAsToolStripMenuItemClick);
            this.toolsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { this.characterMapToolStripMenuItem, this.propertiesToolStripMenuItem });
            this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
            this.toolsToolStripMenuItem.Size = new Size(0x2c, 20);
            this.toolsToolStripMenuItem.Text = "&Tools";
            this.characterMapToolStripMenuItem.Enabled = false;
            this.characterMapToolStripMenuItem.Name = "characterMapToolStripMenuItem";
            this.characterMapToolStripMenuItem.Size = new Size(0x9d, 0x16);
            this.characterMapToolStripMenuItem.Text = "Character &Map...";
            this.characterMapToolStripMenuItem.Click += new EventHandler(this.CharacterMapToolStripMenuItemClick);
            this.propertiesToolStripMenuItem.Enabled = false;
            this.propertiesToolStripMenuItem.Name = "propertiesToolStripMenuItem";
            this.propertiesToolStripMenuItem.Size = new Size(0x9d, 0x16);
            this.propertiesToolStripMenuItem.Text = "&Properties...";
            this.propertiesToolStripMenuItem.Click += new EventHandler(this.PropertiesToolStripMenuItemClick);
            this.helpToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { this.aboutToolStripMenuItem });
            this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
            this.helpToolStripMenuItem.Size = new Size(40, 20);
            this.helpToolStripMenuItem.Text = "&Help";
            this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
            this.aboutToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.aboutToolStripMenuItem.Text = "&About";
            this.aboutToolStripMenuItem.Click += new EventHandler(this.AboutToolStripMenuItemClick);
            this.panelDialogBox.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top;
            this.panelDialogBox.Location = new Point(12, 190);
            this.panelDialogBox.Name = "panelDialogBox";
            this.panelDialogBox.Size = new Size(300, 0xb2);
            this.panelDialogBox.TabIndex = 1;
            this.panelDialogBox.Paint += new PaintEventHandler(this.PanelTilePaint);
            this.panelDialogBox.Resize += new EventHandler(this.PanelDialogBoxResize);
            this.textBoxLine.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top;
            this.textBoxLine.Location = new Point(12, 0x35);
            this.textBoxLine.MaxLength = 0xf423f;
            this.textBoxLine.Multiline = true;
            this.textBoxLine.Name = "textBoxLine";
            this.textBoxLine.ScrollBars = ScrollBars.Vertical;
            this.textBoxLine.Size = new Size(300, 0x83);
            this.textBoxLine.TabIndex = 2;
            this.textBoxLine.TextChanged += new EventHandler(this.TextBoxTextTextChanged);
            this.saveFileDialog.DefaultExt = "NFTR";
            this.saveFileDialog.Filter = "NFTR files|*.nftr|All files|*.*";
            this.saveFileDialog.Title = "Save Table";
            this.openTableDialog.FileName = "custom.tbl";
            this.openTableDialog.Filter = "Table files|*.tbl|All files|*.*";
            this.saveTableDialog.FileName = "custom.tbl";
            this.saveTableDialog.Filter = "Table files|*.tbl|All files|*.*";
            this.openDumpDialog.Filter = "Bitmap files|*.bmp|All files|*.*";
            this.saveDumpDialog.FileName = "dump.bmp";
            this.saveDumpDialog.Filter = "Bitmap files|*.bmp";
            this.textBoxLineLength.Anchor = AnchorStyles.Right | AnchorStyles.Top;
            this.textBoxLineLength.Location = new Point(280, 0x1b);
            this.textBoxLineLength.MaxLength = 10;
            this.textBoxLineLength.Name = "textBoxLineLength";
            this.textBoxLineLength.Size = new Size(0x20, 20);
            this.textBoxLineLength.TabIndex = 3;
            this.textBoxLineLength.Text = "300";
            this.textBoxLineLength.TextChanged += new EventHandler(this.TextBoxTextChanged);
            this.textBoxLineLength.KeyPress += new KeyPressEventHandler(this.TextBoxKeyPress);
            this.label1.Anchor = AnchorStyles.Right | AnchorStyles.Top;
            this.label1.Location = new Point(0xc1, 30);
            this.label1.Name = "label1";
            this.label1.Size = new Size(0x51, 13);
            this.label1.TabIndex = 4;
            this.label1.Text = "Max line length:";
            this.label2.Anchor = AnchorStyles.Right | AnchorStyles.Top;
            this.label2.Location = new Point(12, 30);
            this.label2.Name = "label2";
            this.label2.Size = new Size(50, 13);
            this.label2.TabIndex = 6;
            this.label2.Text = "Padding:";
            this.textBoxPadding.Anchor = AnchorStyles.Right | AnchorStyles.Top;
            this.textBoxPadding.Location = new Point(0x44, 0x1b);
            this.textBoxPadding.MaxLength = 10;
            this.textBoxPadding.Name = "textBoxPadding";
            this.textBoxPadding.Size = new Size(0x20, 20);
            this.textBoxPadding.TabIndex = 5;
            this.textBoxPadding.Text = "0";
            this.textBoxPadding.TextChanged += new EventHandler(this.TextBoxTextChanged);
            this.textBoxPadding.KeyPress += new KeyPressEventHandler(this.TextBoxKeyPress);
            this.optionsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { this.autoApplyToolStripMenuItem });
            this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
            this.optionsToolStripMenuItem.Size = new Size(0x38, 20);
            this.optionsToolStripMenuItem.Text = "&Options";
            this.autoApplyToolStripMenuItem.Name = "autoApplyToolStripMenuItem";
            this.autoApplyToolStripMenuItem.Size = new Size(0x98, 0x16);
            this.autoApplyToolStripMenuItem.Text = "&Auto Apply";
            this.autoApplyToolStripMenuItem.Click += new EventHandler(this.AutoApplyToolStripMenuItemClick);
            base.AutoScaleDimensions = new SizeF(6f, 13f);
            base.AutoScaleMode = AutoScaleMode.Font;
            base.ClientSize = new Size(0x144, 0x17d);
            base.Controls.Add(this.label2);
            base.Controls.Add(this.textBoxPadding);
            base.Controls.Add(this.label1);
            base.Controls.Add(this.textBoxLineLength);
            base.Controls.Add(this.textBoxLine);
            base.Controls.Add(this.panelDialogBox);
            base.Controls.Add(this.menuStrip1);
            //base.Icon = (Icon) manager.GetObject("$this.Icon");
            base.MainMenuStrip = this.menuStrip1;
            this.MinimumSize = new Size(150, 300);
            base.Name = "MainForm";
            this.Text = "NFTRedit";
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.Load += new EventHandler(MainForm_Load);
            base.ResumeLayout(false);
            base.PerformLayout();
        }

        void MainForm_Load(object sender, EventArgs e)
        {
            this.openFileDialog.FileName = file;
            FileStream input = null;
            input = new FileStream(file, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(input);
            this.font = new NFTRedit.Font(reader);
            this.fileName = file;
            this.UpdateMapForm();
            this.saveToolStripMenuItem.Enabled = true;
            this.saveAsToolStripMenuItem.Enabled = true;
            this.dumpTilesToolStripMenuItem.Enabled = true;
            this.importTilesToolStripMenuItem.Enabled = true;
            this.characterMapToolStripMenuItem.Enabled = true;
            this.propertiesToolStripMenuItem.Enabled = true;
            this.RedrawDialogBox();
            input.Close();
        }

        private void LoadTableToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (this.openTableDialog.ShowDialog() == DialogResult.OK)
            {
                FileStream stream = null;
                stream = new FileStream(this.openTableDialog.FileName, FileMode.Open, FileAccess.Read);
                StreamReader data = new StreamReader(stream, Encoding.Unicode);
                try
                {
                    this.table.Load(data);
                    this.tableFileName = this.openTableDialog.FileName;
                }
                catch (Exception exception)
                {
                    MessageBox.Show("The table could not be loaded.\r\nPlease post the following message on the thread,\r\nalong with the NFTR file you tried to open.");
                    throw exception;
                }
                finally
                {
                    if (stream == null)
                    {
                        stream.Close();
                    }
                }
                this.RedrawDialogBox();
            }
        }

        private void OpenToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (this.openFileDialog.ShowDialog() == DialogResult.OK)
            {
                FileStream input = null;
                input = new FileStream(this.openFileDialog.FileName, FileMode.Open, FileAccess.Read);
                BinaryReader reader = new BinaryReader(input);
                this.font = new NFTRedit.Font(reader);
                this.fileName = this.openFileDialog.FileName;
                this.UpdateMapForm();
                this.saveToolStripMenuItem.Enabled = true;
                this.saveAsToolStripMenuItem.Enabled = true;
                this.dumpTilesToolStripMenuItem.Enabled = true;
                this.importTilesToolStripMenuItem.Enabled = true;
                this.characterMapToolStripMenuItem.Enabled = true;
                this.propertiesToolStripMenuItem.Enabled = true;
                this.RedrawDialogBox();
                input.Close();
            }
        }

        private void PanelDialogBoxResize(object sender, EventArgs e)
        {
            this.textBoxLineLength.Text = "" + this.panelDialogBox.Width;
            this.ResizeDialogBox();
        }

        private void PanelTilePaint(object sender, PaintEventArgs e)
        {
            Graphics graphics = this.panelDialogBox.CreateGraphics();
            graphics.DrawImageUnscaled(this.dialogBuffer, 0, 0);
            graphics.Dispose();
        }

        private void PropertiesToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (this.font == null)
            {
                MessageBox.Show("Open a font file first.");
            }
            else
            {
                try
                {
                    if ((this.propertiesForm == null) || this.propertiesForm.IsDisposed)
                    {
                        this.propertiesForm = new PropertiesForm();
                        this.propertiesForm.Show(this, this.font, this.table);
                    }
                    else
                    {
                        this.propertiesForm.Focus();
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show("The properties window could not be displayed.\r\nMake sure you have the latest .NET Framework installed.\nOtherwise, post the following message in the thread,\r\nalong with the NFTR file you are using.");
                    throw exception;
                }
            }
        }

        private void RawBytesToolStripMenuItemClick(object sender, EventArgs e)
        {
            this.mode = 0;
            this.rawBytesToolStripMenuItem.Checked = true;
            this.shiftJISToolStripMenuItem.Checked = false;
            this.unicodeLEToolStripMenuItem.Checked = false;
            this.unicodeBEToolStripMenuItem.Checked = false;
            this.customToolStripMenuItem.Checked = false;
            this.RedrawDialogBox();
        }

        public void RedrawDialogBox()
        {
            if (this.mode == 0)
            {
                this.RedrawDialogBoxRaw();
            }
            else if (this.mode == 1)
            {
                this.RedrawDialogBoxEncoded(Encoding.GetEncoding("Shift_JIS"));
            }
            else if (this.mode == 2)
            {
                this.RedrawDialogBoxEncoded(Encoding.BigEndianUnicode);
            }
            else if (this.mode == 3)
            {
                this.RedrawDialogBoxEncoded(Encoding.Unicode);
            }
            else
            {
                this.RedrawDialogBoxCustom();
            }
        }

        private void RedrawDialogBoxCustom()
        {
            if (this.font != null)
            {
                string text = this.textBoxLine.Text;
                char[] chArray = text.ToCharArray();
                int num = 3;
                int num2 = 3;
                int num3 = num;
                int y = num2;
                int num5 = 0x10;
                int num6 = ((int) Math.Ceiling((double) (((this.panelDialogBox.Height * 1.0) / ((double) num5)) - 1.0))) * num5;
                string str2 = (this.textBoxLineLength.Text.Length > 0) ? this.textBoxLineLength.Text : "0";
                string str3 = (this.textBoxPadding.Text.Length > 0) ? this.textBoxPadding.Text : "0";
                int num7 = Convert.ToInt32(str2) - num;
                int num8 = Convert.ToInt32(str3);
                Bitmap image = new Bitmap(this.backBuffer);
                Graphics graphics = Graphics.FromImage(image);
                graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
                for (int i = 0; i < chArray.Length; i++)
                {
                    if (y > num6)
                    {
                        break;
                    }
                    if (((i + 1) < text.Length) && text.Substring(i, 2).Equals(@"\n"))
                    {
                        num3 = num;
                        y += num5;
                        i++;
                    }
                    else if (((i + 2) < text.Length) && text.Substring(i, 2).Equals("\r\n"))
                    {
                        num3 = num;
                        y += num5;
                        i++;
                    }
                    else if (((i + 3) < text.Length) && text.Substring(i, 4).Equals(@"\r\n"))
                    {
                        num3 = num;
                        y += num5;
                        i += 3;
                    }
                    else if (((i + 3) < text.Length) && text.Substring(i, 4).Equals("<br>"))
                    {
                        num3 = num;
                        y += num5;
                        i += 3;
                    }
                    else if (this.table.Exists(chArray[i]))
                    {
                        ushort codeByChar = this.table.GetCodeByChar(chArray[i]);
                        Character tileByCode = this.font.GetTileByCode(codeByChar);
                        if (tileByCode != null)
                        {
                            int width = tileByCode.Width;
                            int height = tileByCode.Height;
                            if ((num3 + width) > num7)
                            {
                                num3 = num;
                                y += num5;
                            }
                            if (y > num6)
                            {
                                break;
                            }
                            Rectangle destRect = new Rectangle(num3 + tileByCode.OffsetX, y, width, height);
                            graphics.DrawImage(this.Reorient(tileByCode), destRect, 0, 0, width, height, GraphicsUnit.Pixel);
                            num3 += width + num8;
                        }
                    }
                }
                graphics.Dispose();
                graphics = Graphics.FromImage(this.dialogBuffer);
                graphics.DrawImageUnscaled(image, 0, 0);
                graphics.Dispose();
                this.panelDialogBox.Invalidate();
            }
        }

        private void RedrawDialogBoxEncoded(Encoding encoding)
        {
            if (this.font != null)
            {
                string text = this.textBoxLine.Text;
                char[] chars = text.ToCharArray();
                int num = 3;
                int num2 = 3;
                int num3 = num;
                int y = num2;
                int num5 = 0x10;
                int num6 = ((int) Math.Ceiling((double) (((this.panelDialogBox.Height * 1.0) / ((double) num5)) - 1.0))) * num5;
                string str2 = (this.textBoxLineLength.Text.Length > 0) ? this.textBoxLineLength.Text : "0";
                string str3 = (this.textBoxPadding.Text.Length > 0) ? this.textBoxPadding.Text : "0";
                int num7 = Convert.ToInt32(str2) - num;
                int num8 = Convert.ToInt32(str3);
                Bitmap image = new Bitmap(this.backBuffer);
                Graphics graphics = Graphics.FromImage(image);
                graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
                for (int i = 0; i < chars.Length; i++)
                {
                    if (y > num6)
                    {
                        break;
                    }
                    if (((i + 1) < text.Length) && text.Substring(i, 2).Equals(@"\n"))
                    {
                        num3 = num;
                        y += num5;
                        i++;
                    }
                    else if (((i + 2) < text.Length) && text.Substring(i, 2).Equals("\r\n"))
                    {
                        num3 = num;
                        y += num5;
                        i++;
                    }
                    else if (((i + 3) < text.Length) && text.Substring(i, 4).Equals(@"\r\n"))
                    {
                        num3 = num;
                        y += num5;
                        i += 3;
                    }
                    else if (((i + 3) < text.Length) && text.Substring(i, 4).Equals("<br>"))
                    {
                        num3 = num;
                        y += num5;
                        i += 3;
                    }
                    else
                    {
                        byte[] buffer = encoding.GetBytes(chars, i, 1);
                        ushort code = 0;
                        if (buffer.Length == 1)
                        {
                            code = buffer[0];
                        }
                        else if (buffer.Length == 2)
                        {
                            code = (ushort) ((buffer[0] << 8) + buffer[1]);
                        }
                        Character tileByCode = this.font.GetTileByCode(code);
                        if (tileByCode != null)
                        {
                            int width = tileByCode.Width;
                            int height = tileByCode.Height;
                            if ((num3 + width) > num7)
                            {
                                num3 = num;
                                y += num5;
                            }
                            if (y > num6)
                            {
                                break;
                            }
                            Rectangle destRect = new Rectangle(num3 + tileByCode.OffsetX, y, width, height);
                            graphics.DrawImage(this.Reorient(tileByCode), destRect, 0, 0, width, height, GraphicsUnit.Pixel);
                            num3 += width + num8;
                        }
                    }
                }
                graphics.Dispose();
                graphics = Graphics.FromImage(this.dialogBuffer);
                graphics.DrawImageUnscaled(image, 0, 0);
                graphics.Dispose();
                this.panelDialogBox.Invalidate();
            }
        }

        private void RedrawDialogBoxRaw()
        {
            if (this.font != null)
            {
                string text = this.textBoxLine.Text;
                ushort[] numArray = new ushort[text.Length / 4];
                for (int i = 0; i < numArray.Length; i++)
                {
                    string str2 = text.Substring((4 * i) + 2, 2) + text.Substring(4 * i, 2);
                    try
                    {
                        numArray[i] = Convert.ToUInt16(str2, 0x10);
                    }
                    catch (Exception)
                    {
                        numArray[i] = 0;
                    }
                }
                int num2 = 3;
                int num3 = 3;
                int num4 = num2;
                int y = num3;
                int num6 = 0x10;
                int num7 = ((int) Math.Ceiling((double) (((this.panelDialogBox.Height * 1.0) / ((double) num6)) - 1.0))) * num6;
                string str3 = (this.textBoxLineLength.Text.Length > 0) ? this.textBoxLineLength.Text : "0";
                string str4 = (this.textBoxPadding.Text.Length > 0) ? this.textBoxPadding.Text : "0";
                int num8 = Convert.ToInt32(str3) - num2;
                int num9 = Convert.ToInt32(str4);
                Bitmap image = new Bitmap(this.backBuffer);
                Graphics graphics = Graphics.FromImage(image);
                graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
                for (int j = 0; j < numArray.Length; j++)
                {
                    if (y > num7)
                    {
                        break;
                    }
                    Character tileByCode = this.font.GetTileByCode(numArray[j]);
                    if (tileByCode != null)
                    {
                        int width = tileByCode.Width;
                        int height = tileByCode.Height;
                        if ((num4 + width) > num8)
                        {
                            num4 = num2;
                            y += num6;
                        }
                        if (y > num7)
                        {
                            break;
                        }
                        Rectangle destRect = new Rectangle(num4 + tileByCode.OffsetX, y, width, height);
                        graphics.DrawImage(this.Reorient(tileByCode), destRect, 0, 0, width, height, GraphicsUnit.Pixel);
                        num4 += width + num9;
                    }
                }
                graphics.Dispose();
                graphics = Graphics.FromImage(this.dialogBuffer);
                graphics.DrawImageUnscaled(image, 0, 0);
                graphics.Dispose();
                this.panelDialogBox.Invalidate();
            }
        }

        private Bitmap Reorient(Character character)
        {
            Bitmap bitmap = (Bitmap) character.Tile.Clone();
            if (this.font.Orientation == 2)
            {
                bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                return bitmap;
            }
            if (this.font.Orientation == 6)
            {
                bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
            }
            return bitmap;
        }

        private void ResizeDialogBox()
        {
            if (this.panelDialogBox.Height != 0)
            {
                if (this.backBuffer != null)
                {
                    this.backBuffer.Dispose();
                }
                this.backBuffer = new Bitmap(this.panelDialogBox.Width, this.panelDialogBox.Height);
                if (this.dialogBuffer != null)
                {
                    this.dialogBuffer.Dispose();
                }
                this.dialogBuffer = new Bitmap(this.panelDialogBox.Width, this.panelDialogBox.Height);
                Graphics graphics = Graphics.FromImage(this.backBuffer);
                graphics.Clear(this.BackColor);
                graphics.Dispose();
                this.RedrawDialogBox();
            }
        }

        public void ResizeTiles(byte w, byte h)
        {
            if (this.font != null)
            {
                this.font.ResizeTiles(w, h);
                this.UpdateMapForm();
            }
        }

        private void SaveAsToolStripMenuItemClick(object sender, EventArgs e)
        {
            this.saveFileDialog.FileName = this.fileName;
            if (this.saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                FileStream output = new FileStream(this.saveFileDialog.FileName, FileMode.Create, FileAccess.Write);
                BinaryWriter writer = new BinaryWriter(output);
                this.font.Save(writer);
                writer.Close();
                this.fileName = this.saveFileDialog.FileName;
            }
        }

        private void SaveTableAsToolStripMenuItemClick(object sender, EventArgs e)
        {
            this.saveTableDialog.FileName = this.tableFileName;
            if (this.saveTableDialog.ShowDialog() == DialogResult.OK)
            {
                FileStream stream = null;
                stream = new FileStream(this.saveTableDialog.FileName, FileMode.Create, FileAccess.Write);
                StreamWriter data = new StreamWriter(stream, Encoding.Unicode);
                this.table.Save(data);
                data.Close();
                this.tableFileName = this.saveTableDialog.FileName;
            }
        }

        private void SaveTableToolStripMenuItemClick(object sender, EventArgs e)
        {
            FileStream stream = new FileStream(this.tableFileName, FileMode.Create, FileAccess.Write);
            StreamWriter data = new StreamWriter(stream, Encoding.Unicode);
            this.table.Save(data);
            data.Close();
        }

        private void SaveToolStripMenuItemClick(object sender, EventArgs e)
        {
            FileStream output = new FileStream(this.fileName, FileMode.Create, FileAccess.Write);
            BinaryWriter writer = new BinaryWriter(output);
            this.font.Save(writer);
            writer.Close();
        }

        private void ShiftJISToolStripMenuItemClick(object sender, EventArgs e)
        {
            this.mode = 1;
            this.rawBytesToolStripMenuItem.Checked = false;
            this.shiftJISToolStripMenuItem.Checked = true;
            this.unicodeLEToolStripMenuItem.Checked = false;
            this.unicodeBEToolStripMenuItem.Checked = false;
            this.customToolStripMenuItem.Checked = false;
            this.RedrawDialogBox();
        }

        private void TextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar != '\b') && !this.validDec.Contains(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void TextBoxLineLengthTextChanged(object sender, EventArgs e)
        {
            if (this.textBoxLineLength.Text.Length > 0)
            {
                this.RedrawDialogBox();
            }
        }

        private void TextBoxTextChanged(object sender, EventArgs e)
        {
            TextBox box = sender as TextBox;
            if (box.Text.Length == 0)
            {
                box.Text = "0";
                box.SelectAll();
            }
            this.RedrawDialogBox();
        }

        private void TextBoxTextTextChanged(object sender, EventArgs e)
        {
            this.RedrawDialogBox();
        }

        private void UnicodeBEToolStripMenuItemClick(object sender, EventArgs e)
        {
            this.mode = 3;
            this.rawBytesToolStripMenuItem.Checked = false;
            this.shiftJISToolStripMenuItem.Checked = false;
            this.unicodeLEToolStripMenuItem.Checked = false;
            this.unicodeBEToolStripMenuItem.Checked = true;
            this.customToolStripMenuItem.Checked = false;
            this.RedrawDialogBox();
        }

        private void UnicodeLEToolStripMenuItemClick(object sender, EventArgs e)
        {
            this.mode = 2;
            this.rawBytesToolStripMenuItem.Checked = false;
            this.shiftJISToolStripMenuItem.Checked = false;
            this.unicodeLEToolStripMenuItem.Checked = true;
            this.unicodeBEToolStripMenuItem.Checked = false;
            this.customToolStripMenuItem.Checked = false;
            this.RedrawDialogBox();
        }

        private void UpdateMapForm()
        {
            if ((this.mapForm != null) && !this.mapForm.IsDisposed)
            {
                Point location = this.mapForm.Location;
                this.mapForm.Close();
                this.mapForm = new MapForm();
                this.mapForm.Show(this, this.font, this.table);
                this.mapForm.Location = location;
            }
        }
    }
}

